<?php

namespace app\common\cachemodel\ai_chat_room;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class AiChatTag extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_tag';

    protected $cacheModel = 'ai_chat_room.chat_tag';

    public function getChatTagData(int $type)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('title_options', $type)->setCacheType('string')
            ->getDataAndSet(function () use ($type)
            {
                try
                {
                    $titleData = $this->where(['rtype' => $type, 'type' => 1, 'status' => 1])->column('*', 'id');
                    $optionData = $this->where(['rtype' => $type, 'type' => 2, 'status' => 1])->column('*', 'id');

                    $titlePage = [];
                    $titlePageNode = [];
                    foreach ($titleData as $titleDatum)
                    {
                        if (!$titleDatum['pid'])
                        {
                            $titlePage[$titleDatum['page']] = $titleDatum;
                        } else
                        {
                            $titlePageNode[$titleDatum['pid']] = $titleDatum;
                        }
                    }
                    $optionList = [];
                    foreach ($optionData as $optionDatum)
                    {
                        $optionList[$optionDatum['pid'] . ':' . $optionDatum['pid2']][] = $optionDatum;
                    }

                    $resData = [];
                    foreach ($titlePage as $item)
                    {
                        $oList = [];
                        $oIds = [];
                        foreach ($optionList[$item['id'] . ':0'] as $optionItem)
                        {
                            $node = null;
                            if (isset($titlePageNode[$item['id']]) && isset($optionList[$titlePageNode[$item['id']]['id'] . ':' . $optionItem['id']]))
                            {
                                $titleItem = $titlePageNode[$optionItem['pid']];
                                $oList2 = [];
                                $oIds2 = [];
                                foreach ($optionList[$titlePageNode[$item['id']]['id'] . ':' . $optionItem['id']] as $optionItem2)
                                {
                                    $oList2[] = [
                                        'id' => (int)$optionItem2['id'],
                                        'name' => $optionItem2['name'],
                                        'is_selected' => 0,
                                        'icon' => $optionItem2['icon'],
                                    ];
                                    $oIds2[] = (int)$optionItem2['id'];
                                }
                                if ($oList2)
                                {
                                    $node = [
                                        'id' => $titleItem['id'],
                                        'title' => $titleItem['name'],
                                        'title_desc' => $titleItem['name_desc'],
                                        'key' => $titleItem['key'],
                                        'max_select_num' => (int)$titleItem['max_select_num'],
                                        'is_match_astr' => (int)$titleItem['is_match_astr'],
                                        'is_match_option' => (int)$titleItem['is_match_option'],
                                        'option_list' => $oList2,
                                        'option_ids' => $oIds2,
                                    ];
                                }
                            }
                            $oList[] = [
                                'id' => (int)$optionItem['id'],
                                'name' => $optionItem['name'],
                                'is_selected' => 0,
                                'icon' => $optionItem['icon'],
                                'node' => $node,
                            ];
                            $oIds[] = (int)$optionItem['id'];
                        }

                        $resData[] = [
                            'id' => $item['id'],
                            'title' => $item['name'],
                            'title_desc' => $item['name_desc'],
                            'key' => $item['key'],
                            'max_select_num' => (int)$item['max_select_num'],
                            'is_match_astr' => (int)$item['is_match_astr'],
                            'is_match_option' => (int)$item['is_match_option'],
                            'option_list' => $oList,
                            'option_ids' => $oIds,
                        ];
                    }

                    return json_encode($resData, JSON_UNESCAPED_UNICODE);
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    return '';
                }
            }, [], 'title_options');

        $data = $data ? json_decode($data, true) : [];

        return $data;
    }

    public function getChatDescData(int $type, array $configData)
    {
        $ids = [];
        switch ($type)
        {
            case 1:
            case 4:
                $ids = $configData['option10']['ids'] ?? [];
                if (isset($configData['option20']['ids']))
                {
                    $ids = array_merge($ids, $configData['option20']['ids']);
                }
                break;
            case 2:
            case 5:
                $ids = $configData['option10']['ids'] ?? [];
                if (isset($configData['option30']['ids']))
                {
                    $ids = array_merge($ids, $configData['option30']['ids']);
                }
                break;
            case 3:
            case 6:
                $ids = $configData['option10']['ids'] ?? [];
                break;
            // case 4:
            //     $ids = $configData['option10']['ids'] ?? [];
            //     if (isset($configData['option20']['ids']))
            //     {
            //         $ids = array_merge($ids, $configData['option20']['ids']);
            //     }
            //     break;
            // case 5:
            //     $ids = $configData['option10']['ids'] ?? [];
            //     if (isset($configData['option30']['ids']))
            //     {
            //         $ids = array_merge($ids, $configData['option30']['ids']);
            //     }
            //     break;
            // case 6:
            //     $ids = $configData['option10']['ids'] ?? [];
            //     break;
            default:
                return '';
        }

        $tagData = $ids ? $this->batchGetInfoByIds($ids) : [];

        $tagNames = [];
        foreach ($ids as $idItem)
        {
            if (isset($tagData[$idItem]['name']))
            {
                $tagNames[] = $tagData[$idItem]['name'];
            }
        }

        return implode(' | ', $tagNames);
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        // 获取未删除 的数据
        $where = ['id' => ['in', $ids]];
        try
        {
            $data = $this->where($where)->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'rtype', 'type', 'status', 'page', 'pid', 'pid2', 'max_select_num', 'is_match_astr', 'is_match_option', 'create_time', 'update_time']);
        }

        return $data;
    }

    public function getConfigTagsData(array $configs)
    {
        $ids = [];
        foreach ($configs as $configItem)
        {
            if (isset($configItem['ids']) && $configItem['ids'])
            {
                $ids = array_merge($ids, $configItem['ids']);
            }
        }

        $tagDatas = $ids ? $this->batchGetInfoByIds($ids, 'name') : [];
        $resTagNames = [];
        foreach ($configs as $configItem)
        {
            if (isset($configItem['ids']))
            {
                foreach ($configItem['ids'] as $idItem)
                {
                    if (isset($tagDatas[$idItem]['name']))
                    {
                        $resTagNames[] = $tagDatas[$idItem]['name'];
                    }
                }
            }
        }

        return $resTagNames;
    }
}